package com.lzb.permanentcalendar.activity;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzb.permanentcalendar.BaseAc;
import com.lzb.permanentcalendar.HomeActivity;
import com.lzb.permanentcalendar.R;
import com.lzb.permanentcalendar.bean.ScheduleBean;
import com.lzb.permanentcalendar.databinding.ActivityAddScheduleBinding;
import com.lzb.permanentcalendar.dialog.ReqPermissionDialog;
import com.lzb.permanentcalendar.dialog.ScheduleTypeDialog;
import com.lzb.permanentcalendar.dialog.SelDateDialog;
import com.lzb.permanentcalendar.dialog.SelRemindDialog;
import com.lzb.permanentcalendar.dialog.SelRepeatDialog;
import com.lzb.permanentcalendar.dialog.SelTimeDialog;
import com.lzb.permanentcalendar.utils.AppSpUtils;
import com.nlf.calendar.Lunar;
import com.nlf.calendar.Solar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class AddScheduleActivity extends BaseAc<ActivityAddScheduleBinding> implements View.OnClickListener {

    public static ScheduleBean scheduleBean;
    public static String type;
    private long startDate, endDate, startTime, endTime;
    private boolean isAllDay = true;
    private ScheduleTypeDialog scheduleTypeDialog;
    private SelDateDialog startDateDialog, endDateDialog;
    private SelTimeDialog startTimeDialog, endTimeDialog;
    private SelRemindDialog selRemindDialog;
    private SelRepeatDialog selRepeatDialog;
    private SimpleDateFormat allDayFormat = new SimpleDateFormat("yyyy年MM月dd EEE");
    private SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy年MM月dd EEE HH:mm");

    @Override
    protected int onCreate() {
        return R.layout.activity_add_schedule;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAddScheduleBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvScheduleType.setOnClickListener(this);
        mDataBinding.ivAllDay.setOnClickListener(this);
        mDataBinding.tvStart.setOnClickListener(this);
        mDataBinding.tvEnd.setOnClickListener(this);
        mDataBinding.tvRemind.setOnClickListener(this);
        mDataBinding.tvRepeat.setOnClickListener(this);
        mDataBinding.tvCompelete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvScheduleType) {//日程类型
            showScheduleTypeDialog();
        } else if (id == R.id.ivAllDay) {//全天
            isAllDay = !isAllDay;
            mDataBinding.ivAllDay.setImageResource(isAllDay ? R.drawable.akai : R.drawable.aguan);
            mDataBinding.tvStart.setText(isAllDay ? TimeUtils.millis2String(startDate, allDayFormat) : TimeUtils.millis2String(startTime, timeFormat));
            mDataBinding.tvEnd.setText(isAllDay ? TimeUtils.millis2String(endDate, allDayFormat) : TimeUtils.millis2String(endTime, timeFormat));
        } else if (id == R.id.tvStart) {//开始
            if (isAllDay) {
                showStartDateDialog();
            } else {
                showStartTimeDialog();
            }
        } else if (id == R.id.tvEnd) {//结束
            if (isAllDay) {
                showEndDateDialog();
            } else {
                showEndTimeDialog();
            }
        } else if (id == R.id.tvRemind) {//提醒
            // 检查通知权限
            NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                if (notificationManager.areNotificationsEnabled()) {
                    showSelRemindDialog();
                } else {
                    showReqPermissionDialog();
                }
            }
        } else if (id == R.id.tvRepeat) {//重复
            showSelRepeatDialog();
        } else if (id == R.id.tvCompelete) {//完成
            save();
        }
    }

    @Override
    protected void initData() {
        if (scheduleBean == null) {
            String nowDate = TimeUtils.getNowString(allDayFormat);
            String nowTime = TimeUtils.getNowString(timeFormat);
            startDate = TimeUtils.string2Millis(nowDate, allDayFormat);
            endDate = TimeUtils.string2Millis(nowDate, allDayFormat);
            startTime = TimeUtils.string2Millis(nowTime, timeFormat);
            endTime = TimeUtils.string2Millis(nowTime, timeFormat);
            mDataBinding.tvScheduleType.setText(type);
            mDataBinding.tvStart.setText(nowDate);
            mDataBinding.tvEnd.setText(nowDate);
        } else {
            mDataBinding.tvScheduleType.setText(scheduleBean.getType());
            mDataBinding.etTitle.setText(scheduleBean.getTitle());
            mDataBinding.etRemark.setText(scheduleBean.getRemark());
            isAllDay = scheduleBean.isAllDay();

            if (isAllDay) {
                startDate = scheduleBean.getStartTime();
                endDate = scheduleBean.getEndTime();
                String nowTime = TimeUtils.getNowString(timeFormat);
                startTime = TimeUtils.string2Millis(nowTime, timeFormat);
                endTime = TimeUtils.string2Millis(nowTime, timeFormat);
            } else {
                String nowDate = TimeUtils.getNowString(allDayFormat);
                startDate = TimeUtils.string2Millis(nowDate, allDayFormat);
                endDate = TimeUtils.string2Millis(nowDate, allDayFormat);
                startTime = scheduleBean.getStartTime();
                endTime = scheduleBean.getEndTime();
            }
            mDataBinding.ivAllDay.setImageResource(isAllDay ? R.drawable.akai : R.drawable.aguan);
            mDataBinding.tvStart.setText(isAllDay ? TimeUtils.millis2String(startDate, allDayFormat) : TimeUtils.millis2String(startTime, timeFormat));
            mDataBinding.tvEnd.setText(isAllDay ? TimeUtils.millis2String(endDate, allDayFormat) : TimeUtils.millis2String(endTime, timeFormat));
            mDataBinding.tvRemind.setText(scheduleBean.getRemindType());
            mDataBinding.tvRepeat.setText(scheduleBean.getRepeatType());
        }
    }

    private void save() {
        String title = mDataBinding.etTitle.getText().toString().trim();
        String remark = mDataBinding.etRemark.getText().toString().trim();

        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort(getText(R.string.please_input_title));
            return;
        }

        if (TextUtils.isEmpty(remark)) {
            ToastUtils.showShort(getText(R.string.please_input_remark));
            return;
        }

        if (isAllDay) {
            if (startDate > endDate) {
                ToastUtils.showShort(getString(R.string.end_not_earlier_start));
                return;
            }
        } else {
            if (startTime > endTime) {
                ToastUtils.showShort(getString(R.string.end_not_earlier_start));
                return;
            }
        }

        String scheduleType = mDataBinding.tvScheduleType.getText().toString();
        String remindType = mDataBinding.tvRemind.getText().toString();
        String repeatType = mDataBinding.tvRepeat.getText().toString();
        if (scheduleBean == null) {
            scheduleBean = new ScheduleBean();
            scheduleBean.setId(TimeUtils.getNowString());
            scheduleBean.setType(scheduleType);
            scheduleBean.setTitle(title);
            scheduleBean.setRemark(remark);
            scheduleBean.setAllDay(isAllDay);
            scheduleBean.setRemindType(remindType);
            scheduleBean.setRepeatType(repeatType);
            if (isAllDay) {
                scheduleBean.setStartTime(startDate);
                scheduleBean.setEndTime(endDate);
                if (remindType.equals(getString(R.string.remind_type1))) {
                    scheduleBean.setRemindTime(startDate);
                } else if (remindType.equals(getString(R.string.remind_type2))) {
                    String timeStr = TimeUtils.millis2String(startDate, allDayFormat) + " 9:00";
                    scheduleBean.setRemindTime(TimeUtils.string2Millis(timeStr, timeFormat));
                } else if (remindType.equals(getString(R.string.remind_type3))) {
                    String timeStr = TimeUtils.millis2String(startDate, allDayFormat) + " 8:55";
                    scheduleBean.setRemindTime(TimeUtils.string2Millis(timeStr, timeFormat));
                } else if (remindType.equals(getString(R.string.remind_type4))) {
                    String timeStr = TimeUtils.millis2String(startDate, allDayFormat) + " 8:45";
                    scheduleBean.setRemindTime(TimeUtils.string2Millis(timeStr, timeFormat));
                } else if (remindType.equals(getString(R.string.remind_type5))) {
                    String timeStr = TimeUtils.millis2String(startDate, allDayFormat) + " 8:30";
                    scheduleBean.setRemindTime(TimeUtils.string2Millis(timeStr, timeFormat));
                }
            } else {
                scheduleBean.setStartTime(startTime);
                scheduleBean.setEndTime(endTime);
                Calendar calendar = Calendar.getInstance();
                if (remindType.equals(getString(R.string.remind_type1))) {
                    calendar.setTimeInMillis(startTime);
                } else if (remindType.equals(getString(R.string.remind_type2))) {
                    calendar.setTimeInMillis(startTime);
                } else if (remindType.equals(getString(R.string.remind_type3))) {
                    calendar.setTimeInMillis(startTime);
                    calendar.add(Calendar.MINUTE, -5);
                } else if (remindType.equals(getString(R.string.remind_type4))) {
                    calendar.setTimeInMillis(startTime);
                    calendar.add(Calendar.MINUTE, -15);
                } else if (remindType.equals(getString(R.string.remind_type5))) {
                    calendar.setTimeInMillis(startTime);
                    calendar.add(Calendar.MINUTE, -30);
                }
                scheduleBean.setRemindTime(calendar.getTimeInMillis());
            }
            List<ScheduleBean> listSave = new ArrayList<>();
            listSave.add(scheduleBean);
            List<ScheduleBean> listSp = AppSpUtils.getScheduleList();
            if (listSp != null && listSp.size() > 0) {
                listSp.addAll(listSave);
                AppSpUtils.saveScheduleList(listSp);
            } else {
                AppSpUtils.saveScheduleList(listSave);
            }
            ToastUtils.showShort(getString(R.string.save_suc));
            startActivity(HomeActivity.class);
        } else {
            scheduleBean.setType(scheduleType);
            scheduleBean.setTitle(title);
            scheduleBean.setRemark(remark);
            scheduleBean.setAllDay(isAllDay);
            scheduleBean.setRemindType(remindType);
            scheduleBean.setRepeatType(repeatType);
            if (isAllDay) {
                scheduleBean.setStartTime(startDate);
                scheduleBean.setEndTime(endDate);
                if (remindType.equals(getString(R.string.remind_type1))) {
                    scheduleBean.setRemindTime(startDate);
                } else if (remindType.equals(getString(R.string.remind_type2))) {
                    String timeStr = TimeUtils.millis2String(startDate, allDayFormat) + " 9:00";
                    scheduleBean.setRemindTime(TimeUtils.string2Millis(timeStr, timeFormat));
                } else if (remindType.equals(getString(R.string.remind_type3))) {
                    String timeStr = TimeUtils.millis2String(startDate, allDayFormat) + " 8:55";
                    scheduleBean.setRemindTime(TimeUtils.string2Millis(timeStr, timeFormat));
                } else if (remindType.equals(getString(R.string.remind_type4))) {
                    String timeStr = TimeUtils.millis2String(startDate, allDayFormat) + " 8:45";
                    scheduleBean.setRemindTime(TimeUtils.string2Millis(timeStr, timeFormat));
                } else if (remindType.equals(getString(R.string.remind_type5))) {
                    String timeStr = TimeUtils.millis2String(startDate, allDayFormat) + " 8:30";
                    scheduleBean.setRemindTime(TimeUtils.string2Millis(timeStr, timeFormat));
                }
            } else {
                scheduleBean.setStartTime(startTime);
                scheduleBean.setEndTime(endTime);
                Calendar calendar = Calendar.getInstance();
                if (remindType.equals(getString(R.string.remind_type1))) {
                    calendar.setTimeInMillis(startTime);
                } else if (remindType.equals(getString(R.string.remind_type2))) {
                    calendar.setTimeInMillis(startTime);
                } else if (remindType.equals(getString(R.string.remind_type3))) {
                    calendar.setTimeInMillis(startTime);
                    calendar.add(Calendar.MINUTE, -5);
                } else if (remindType.equals(getString(R.string.remind_type4))) {
                    calendar.setTimeInMillis(startTime);
                    calendar.add(Calendar.MINUTE, -15);
                } else if (remindType.equals(getString(R.string.remind_type5))) {
                    calendar.setTimeInMillis(startTime);
                    calendar.add(Calendar.MINUTE, -30);
                }
                scheduleBean.setRemindTime(calendar.getTimeInMillis());
            }
            List<ScheduleBean> listSp = AppSpUtils.getScheduleList();
            for (int i = 0; i < listSp.size(); i++) {
                ScheduleBean bean = listSp.get(i);
                if (bean.getId().equals(scheduleBean.getId())) {
                    listSp.set(i, scheduleBean);
                    break;
                }
            }
            AppSpUtils.saveScheduleList(listSp);
            ToastUtils.showShort(getString(R.string.save_suc));
            startActivity(HomeActivity.class);
        }
    }

    private void showScheduleTypeDialog() {
        if (scheduleTypeDialog == null) scheduleTypeDialog = new ScheduleTypeDialog(mContext);
        scheduleTypeDialog.setListener(new ScheduleTypeDialog.Ilistener() {
            @Override
            public void click(String name) {
                mDataBinding.tvScheduleType.setText(name);
            }
        });
        scheduleTypeDialog.show();
    }

    private void showStartDateDialog() {
        if (startDateDialog == null) startDateDialog = new SelDateDialog(mContext);
        startDateDialog.setListener(new SelDateDialog.Ilistener() {
            @Override
            public void clickConfirm(int type, int year, int mo, int days) {
                if (type == 0) {
                    startDate = TimeUtils.string2Millis(year + "-" + (mo < 10 ? "0" + mo : mo) + "-" + (days < 10 ? "0" + days : days), new SimpleDateFormat("yyyy-MM-dd"));
                    mDataBinding.tvStart.setText(TimeUtils.millis2String(startDate, allDayFormat));
                } else if (type == 1) {
                    Lunar lunar = new Lunar(year, mo, days);
                    // 转换为阳历
                    Solar solar = lunar.getSolar();
                    startDate = TimeUtils.string2Millis(solar.getYear() + "-" + (solar.getMonth() < 10 ? "0" + solar.getMonth() : solar.getMonth()) + "-" + (solar.getDay() < 10 ? "0" + solar.getDay() : solar.getDay()), new SimpleDateFormat("yyyy-MM-dd"));
                    mDataBinding.tvStart.setText(TimeUtils.millis2String(startDate, allDayFormat));
                }
            }
        });
        startDateDialog.show();
    }

    private void showEndDateDialog() {
        if (endDateDialog == null) endDateDialog = new SelDateDialog(mContext);
        endDateDialog.setListener(new SelDateDialog.Ilistener() {
            @Override
            public void clickConfirm(int type, int year, int mo, int days) {
                if (type == 0) {
                    endDate = TimeUtils.string2Millis(year + "-" + (mo < 10 ? "0" + mo : mo) + "-" + (days < 10 ? "0" + days : days), new SimpleDateFormat("yyyy-MM-dd"));
                    mDataBinding.tvEnd.setText(TimeUtils.millis2String(startDate, allDayFormat));
                } else if (type == 1) {
                    Lunar lunar = new Lunar(year, mo, days);
                    // 转换为阳历
                    Solar solar = lunar.getSolar();
                    endDate = TimeUtils.string2Millis(solar.getYear() + "-" + (solar.getMonth() < 10 ? "0" + solar.getMonth() : solar.getMonth()) + "-" + (solar.getDay() < 10 ? "0" + solar.getDay() : solar.getDay()), new SimpleDateFormat("yyyy-MM-dd"));
                    mDataBinding.tvEnd.setText(TimeUtils.millis2String(startDate, allDayFormat));
                }
            }
        });
        endDateDialog.show();
    }

    private void showStartTimeDialog() {
        if (startTimeDialog == null) startTimeDialog = new SelTimeDialog(mContext);
        startTimeDialog.setListener(new SelTimeDialog.Ilistener() {
            @Override
            public void clickConfirm(int type, int year, int mo, int days, int hour, int min) {
                if (type == 0) {
                    startTime = TimeUtils.string2Millis(year + "-" + (mo < 10 ? "0" + mo : mo) + "-" + (days < 10 ? "0" + days : days) + " " + (hour < 10 ? "0" + hour : hour) + ":" + (min < 10 ? "0" + min : min), new SimpleDateFormat("yyyy-MM-dd HH:mm"));
                    mDataBinding.tvStart.setText(TimeUtils.millis2String(startTime, timeFormat));
                } else if (type == 1) {
                    Lunar lunar = new Lunar(year, mo, days);
                    // 转换为阳历
                    Solar solar = lunar.getSolar();
                    startTime = TimeUtils.string2Millis(solar.getYear() + "-" + (solar.getMonth() < 10 ? "0" + solar.getMonth() : solar.getMonth()) + "-" + (solar.getDay() < 10 ? "0" + solar.getDay() : solar.getDay()) + " " + (hour < 10 ? "0" + hour : hour) + ":" + (min < 10 ? "0" + min : min), new SimpleDateFormat("yyyy-MM-dd HH:mm"));
                    mDataBinding.tvStart.setText(TimeUtils.millis2String(startTime, timeFormat));
                }
            }
        });
        startTimeDialog.show();
    }

    private void showEndTimeDialog() {
        if (endTimeDialog == null) endTimeDialog = new SelTimeDialog(mContext);
        endTimeDialog.setListener(new SelTimeDialog.Ilistener() {
            @Override
            public void clickConfirm(int type, int year, int mo, int days, int hour, int min) {
                if (type == 0) {
                    endTime = TimeUtils.string2Millis(year + "-" + (mo < 10 ? "0" + mo : mo) + "-" + (days < 10 ? "0" + days : days) + " " + (hour < 10 ? "0" + hour : hour) + ":" + (min < 10 ? "0" + min : min), new SimpleDateFormat("yyyy-MM-dd HH:mm"));
                    mDataBinding.tvEnd.setText(TimeUtils.millis2String(endTime, timeFormat));
                } else if (type == 1) {
                    Lunar lunar = new Lunar(year, mo, days);
                    // 转换为阳历
                    Solar solar = lunar.getSolar();
                    endTime = TimeUtils.string2Millis(solar.getYear() + "-" + (solar.getMonth() < 10 ? "0" + solar.getMonth() : solar.getMonth()) + "-" + (solar.getDay() < 10 ? "0" + solar.getDay() : solar.getDay()) + " " + (hour < 10 ? "0" + hour : hour) + ":" + (min < 10 ? "0" + min : min), new SimpleDateFormat("yyyy-MM-dd HH:mm"));
                    mDataBinding.tvStart.setText(TimeUtils.millis2String(endTime, timeFormat));
                }
            }
        });
        endTimeDialog.show();
    }

    private void showSelRemindDialog() {
        if (selRemindDialog == null) selRemindDialog = new SelRemindDialog(mContext);
        selRemindDialog.setListener(new SelRemindDialog.Ilistener() {

            @Override
            public void clickConfirm(String name) {
                mDataBinding.tvRemind.setText(name);
            }
        });
        selRemindDialog.show();
    }

    private void showSelRepeatDialog() {
        if (selRepeatDialog == null) selRepeatDialog = new SelRepeatDialog(mContext);
        selRepeatDialog.setListener(new SelRepeatDialog.Ilistener() {

            @Override
            public void clickConfirm(String name) {
                mDataBinding.tvRepeat.setText(name);
            }
        });
        selRepeatDialog.show();
    }

    private void showReqPermissionDialog() {
        ReqPermissionDialog reqPermissionDialog = new ReqPermissionDialog(mContext);
        reqPermissionDialog.setContent(getString(R.string.get_notification_permission));
        reqPermissionDialog.setListener(new ReqPermissionDialog.Ilistener() {
            @Override
            public void clickConfirm() {
                // 一行代码搞定（推荐）
                Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                        .putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
                startActivity(intent);
            }
        });
        reqPermissionDialog.show();
    }

}